<template>
  <ul v-if="images.length > 0" id="viewer-images" class="com-global-viewer">
    <li>
      <img v-for="v in images" :key="v" :src="v" class="image" />
    </li>
  </ul>
</template>

<script lang="ts">
import Viewer from 'viewerjs'
import 'viewerjs/dist/viewer.min.css'
import { Vue, Component } from 'vue-property-decorator'
import { UrlClearFormat } from '@/utils/tool'

@Component({
  name: 'ComGlobalViewer'
})
export default class ComGlobalViewer extends Vue {
  /**
   * 图片链接数组
   */
  images = []
  /**
   * 图片显示器对象
   */
  viewer:any = null

  /**
   * 显示图片查看器
   * @param images 图片链接数组
   * @param index 显示索引 默认0
   */
  show (images: any, index = 0) {
    let imageUrls = images
    if (typeof images === 'string') {
      imageUrls = [imageUrls]
    }
    this.images = imageUrls.map((url:string) => {
      return UrlClearFormat(url)
    })
    this.$nextTick(() => {
      this.viewer = new Viewer(document.getElementById('viewer-images') as any, {
        hidden: () => {
          this.close()
        }
      })
      this.viewer.show(index)
    })
  }

  /**
   * 关闭图片查看器
   */
  close () {
    this.viewer = null
    this.images = []
  }
}

</script>

<style lang="less" scoped>
.com-global-viewer {
  width: 0;
  height: 0;
  list-style: none;
  overflow: hidden;
}
</style>
